<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :isDetail="true"
    :showDetailBack="false"
    @ok="handleSubmit"
    @close="clearTable"
  >
    <BasicTable
      v-for="(table, index) in tableListRef"
      :key="index"
      :title="table.title"
      :columns="table.columns"
      :dataSource="table.dataSource"
    />
  </BasicDrawer>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTable } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getFixResidentFieldsList, importBomInventoryList } from '/@/api/opms/fixResident';

  const emit = defineEmits(['success', 'register']);
  const { createMessage } = useMessage();
  let tableListRef = ref<
    {
      title: string;
      columns?: any[];
      dataSource?: any[];
    }[]
  >([]);
  const [registerDrawer, { closeDrawer, setDrawerProps }] = useDrawerInner(async (data) => {
    tableListRef.value = data.tableList;
    setDrawerProps({ confirmLoading: false });
  });

  function clearTable() {
    tableListRef.value = [];
  }

  async function handleSubmit() {
    debugger;
    //反射获取数据
    const excelHeaderOptions = await getFixResidentFieldsList();
    console.log('-->', excelHeaderOptions);
    const findFiled = (title: string): string | undefined =>
      excelHeaderOptions.find((i) => i.label == title)?.value;
    try {
      setDrawerProps({ confirmLoading: true });
      let dataSource = unref(tableListRef)[0].dataSource;
      //将item中文字段 转换 英文字段
      dataSource = dataSource?.map((i) => {
        const obj = {}; //定义一个对象用于转换后返回
        //枚举当前对象的key
        for (const iKey in i) {
          const iValue = i[iKey]; //当前对象的值
          obj[findFiled(iKey) || ''] = iValue; // 将每个中文字段转换为英文字段
        }
        return obj; //返回
      });
      //tableListRef.value[0].dataSource
      const data = await importBomInventoryList(dataSource);
      createMessage.success('导入成功！');

      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
